package com.captain.leetcode.中级.数组;

import java.util.*;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/1/10 16:28
 */
public class 字母异位词分组49 {
    public static void main(String[] args) {
        for (List<String> list : new 字母异位词分组49().groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"})) {
            System.out.println(list.toString());
        }

    }

    public List<List<String>> groupAnagrams(String[] strs) {
        //解题思路
        //1. 将里面的每个字符排序,存入hash,如果相同,则添加,如果不存在,则创建,返回结果
        if (strs == null || strs.length == 0) {
            return null;
        }
        Map<String, List<String>> res = new HashMap<>();
        for (String str : strs) {
            char[] strChars = str.toCharArray();
            Arrays.sort(strChars);
            String key = String.valueOf(strChars);
            if (res.containsKey(key)) {
                res.get(key).add(str);
            } else {
                ArrayList<String> tp = new ArrayList<>();
                tp.add(str);
                res.put(key, tp);
            }
        }
        return new ArrayList<>(res.values());
    }
}
